<?php
/**
 * Created by PhpStorm.
 * User: 胥九庆
 * Date: 2023/01/05
 * Time: 14:19
 */
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Course;
use app\common\tool\Result;
use think\Response;
use app\common\model\CourseOrder as CourseOrderModel;

class CourseOrder extends Base
{
    public function payment(): Response
    {
        $param = $this->request->get();
        $info = Course::where(['id' => $param['course_id'], 'is_del' => 0])->find();
        if (empty($info)) return Result::fail('该课程不存在');
        if ($info->is_free != 2) return Result::fail('该课程不需要支付');
        if (!$info->price || $info->price <= 0) return Result::fail('该课程金额有误');
        $count = CourseOrderModel::where(['course_id' => $param['course_id'], 'uid' => $this->user->id, 'state' => 2, 'is_del' => 0])->count('id');
        if ($count > 0) return Result::fail('您已购买过该课程');
        $result['total_amount'] = $info->price;
        $result['method'] = getPaymentMethod('wechat,alipay,love_bean,chain_bean');

        return Result::success('success', $result);
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        if (!in_array($param['pay_way'], ['wechat', 'alipay']) && md5($param['pay_password']) != $this->user->pay_password) {
            return Result::fail('支付密码错误');
        }

        return Result::fastReturn(CourseOrderModel::submit($param, $this->user));
    }

    public function getList(): Response
    {
        $map = ['uid' => $this->user->id, 'state' => 2, 'is_del' => 0];
        $list = CourseOrderModel::getPageList($map, 'id,sn,course_id,title,img,total_amount,real_amount,pay_way,state,create_time', $this->getPage(), $this->getLimit(), false);

        return Result::fastReturn($list);
    }
}